package cron.core.scheduler.trigger;


import cron.decode.CronSequenceGenerator;
import cron.task.plugin.Task;

import java.util.Date;
import java.util.GregorianCalendar;

/**
 * @author : willian fu
 * @version : 1.0
 * @date : 2021/3/5 0005 17:48
 */
public class CronTrigger extends AbstractTrigger{

    private String cron;

    private CronSequenceGenerator generator;


    public CronTrigger(String cron, Task worker) {
        this.cron = cron;
        this.worker = worker;
        generator = new CronSequenceGenerator(cron);
        nextTime = generator.next(GregorianCalendar.getInstance().getTime());
    }


    @Override
    public boolean isBeTrigger(long count) {
        return this.count <= count;
    }

    @Override
    public void updateRule(Object rule) {
        this.cron = rule.toString();
        generator = new CronSequenceGenerator(this.cron);
        toNext();
    }

    @Override
    public Date getNextTime() {
        //如果超过执行时间
        do {
            nextTime = generator.next(nextTime);
        }while (nextTime.before(GregorianCalendar.getInstance().getTime()));
        return nextTime;
    }

    @Override
    public void run() {
        if (enable){
            worker.doRun();
        }
        super.run();
    }

}
